requireJS(['constant', 'site', 'handlebars'], function (Constant, site, Handlebars) {

    var url = {
        queryOrderAndProduct: "manager/queryOrderInfos.do",
        queryProductForm: "manager/selectProductFormCustom.do",
        selectEducation: "manager/selectEducation.do",
        selectLoanTypeList: "manager/selectLoanTypeList.do",
        selectApplyTermList: "manager/selectApplyTermList.do",
        selectOrderSourceList: "manager/selectOrderSourceList.do",
        selectRepanymentWayList: "manager/selectRepanymentWayList.do",
        selectLoanMethodList: "manager/queryLoanDefineByProductId.do",
        queryFeeRelation: "manager/queryFeeRelationByProductId.do",
        selectAttachmentList: "manager/selectAttachmentAll.do",
        queryNodeOperationRecordForm: "manager/queryNodeOperationRecordForm.do",
        queryNodeOperationRecordValue: "manager/queryNodeOperationRecordValue.do",
        selectMarry: "manager/selectMarry.do",
        queryPlan: "manager/queryPlan.do",
        downloadPicturesZip: "manager/downloadPicturesZip.do",
        ajaxqueryRegion: localStorage.getItem('host') + "manager/ajaxqueryRegion.do",
        getActivitiProccessImage: "manager/getActivitiProccessImage.do",
        selectAttachmentTarget: "manager/selectAttachmentTarget.do",
        Loanedecord:"manager/Loanedecord.do"
    }

    var product_id = getAurlparam('product_id');
    var order_id = getAurlparam('order_id');
    var ari = getAurlparam('ari');
    var status = getAurlparam('status');
    var time = getAurlparam('time');
    var pageCount = 1;
    var pageNum = 0;
    var currentPage = 0;
    var a;
    var frontData = {
        pageNum : 1
    }

    if(status == '1'){
        $("#status").attr('src','static/images/investment_progress3.png');
        $("#is_over").hide();
    }else if(status == '-1'){
        $("#status").attr('src','static/images/investment_progress4.png');
        $("#is_over").show();
    }

    $('.apply_time, .issuing_time').html('时间：'+ time);
    $('.full_mark_time').html('时间：'+ time);

    /**
     * 指定保留的字符数量，用星号代替字符串中间部分字符
     * @param source 源字符串
     * @param reservedNumHalf 要保留的字符数量的一半（前后各一半）
     * @returns {string} 结果字符串
     **/
    function replaceWithAsterisk(source, reservedNumHalf) {
        if (!source) {
            return '';
        }

        var finalReservedNumHalf;
        var mask;
        if (source.length === 1) {
            return source;
        }
        if (source.length === 2) {
            return '*' + source.substr(source.length - 1);
        }
        if (source.length <= 3) {
            finalReservedNumHalf = 1;
            mask = '*';
        } else if (source.length === 4) {
            finalReservedNumHalf = 2;
            mask = '**';
        } else {
            finalReservedNumHalf = reservedNumHalf || 3;
            mask = '***';
        }
        return source.substr(0, finalReservedNumHalf) + mask + source.substr(source.length - finalReservedNumHalf);
    }

    function fillFormData() {
        site.send({
            url: url.queryOrderAndProduct,
            data: {
                order_id: getAurlparam('order_id')
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {

                    var orderDatas = data.content.orderDatas;
                    var productRealDatas = data.content.productRealDatas;
                    var feeDatas = data.content.feeDatas;
                    var personalDatas = data.content.personalDatas;
                    var personalRealDatas = data.content.personalRealDatas;
                    var loanMethodDatas = data.content.loanMethodDatas;

                    $("#apply_money").html("￥" + Constant.tplHelper.AMOUNT_FORMAT(orderDatas.apply_money));
                    $('#loanType_content').html($('#loanType_content option[data-id=' + orderDatas.lt_id + ']').text()).show();
                    $('#repanymentWay_content').html($('#repanymentWay_content option[data-id=' + orderDatas.repayment_way + ']').text());
                    if (orderDatas.at_id) {
                        $('#applyTerm_content').html($('#applyTerm_content option[data-id=' + orderDatas.at_id + ']').text());
                    }
                    if (orderDatas.at_id) {
                        $('#apply_day').html(orderDatas.at_id + '天');
                    }

                    //还款方式为按天收息的特殊判断
                    if (getAurlparam('repayment_way') == '4') {
                        $("#applyTerm_content").hide()
                        $("#apply_day").show();
                    } else {
                        $("#applyTerm_content").show();
                        $("#apply_day").hide();
                    }

                    $('#loanMethod_content').html($('#loanMethod_content input[value=' + orderDatas.loan_way + ']').parent('label').text());
                    $('#orderSource_content').html($('#orderSource_content option[data-id=' + orderDatas.os_id + ']').text() ? $('option[data-id=' + orderDatas.os_id + ']').text() : "未填写");
                    $("#annualized_interest_rate").html(ari + '%');
                    //$('#count span .money').html(orderDatas.interest);
                    $('.public-content-Po').html(orderDatas.loan_number);

                    $("#count span").html('<em>利率：' + orderDatas.interest + '分</em>');

                    $.each(productRealDatas, function (index, item) {
                        var type = item.type
                        $('#apply-message .component[id=' + item.property_id + ']').attr('op_id', item.id);
                        if (item.value) {
                            $('#apply-message .component[id=' + item.property_id + '] .controls').html(replaceWithAsterisk(item.value));
                        }
                        else {
                            $('#apply-message .component[id=' + item.property_id + '] .controls').html('未填写');
                        }
                    })

                    $.each(personalRealDatas, function (index, item) {
                        var type = item.type
                        $('#apply-PersonMess .component[id=' + item.property_id + ']').attr('op_id', item.id);
                        if (item.value) {
                            $('#apply-PersonMess .component[id=' + item.property_id + '] .controls').html(replaceWithAsterisk(item.value));
                        }
                        else {
                            $('#apply-PersonMess .component[id=' + item.property_id + '] .controls').html('未填写');
                        }
                    })

                    //客户固定字段渲染
                    $.each(personalDatas.borrowerDatas, function (i, e) {
                        var a = i + 1;
                        if (i == 0) {
                            $(".personMess:first .realName").parents('td').html("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style='min-width: 68px; display: inline-block'>" + replaceWithAsterisk(e.real_name) + "</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + replaceWithAsterisk(e.id_card) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + replaceWithAsterisk(e.birth_date) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + replaceWithAsterisk(e.cellphone) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + (e.sex === 1 ? '男' : '女'));
                        }
                        else {
                            $(".personMess:last").after('<tr i="' + i + '" class="personMess ng-scope">\n' +
                                '            <td class="ng-binding"><span>*</span>借款人' + a + '</td>\n' +
                                '            <td colspan="7" style="text-align: left">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="min-width: 68px; display: inline-block">' + replaceWithAsterisk(e.real_name) + '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + replaceWithAsterisk(e.id_card) + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + replaceWithAsterisk(e.birth_date) + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + replaceWithAsterisk(e.cellphone) + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + (e.sex === 1 ? '男' : '女') + '</td>\n' +
                                '        </tr>')
                            $('tr[i=' + i + '] input[value=' + e.sex + ']').parent('.sex-radio').addClass('is-checked');
                        }
                    })
                    personalDatas.addr_p_name = personalDatas.addr_p_name ? replaceWithAsterisk(personalDatas.addr_p_name) : ""
                    personalDatas.addr_c_name = personalDatas.addr_c_name ? replaceWithAsterisk(personalDatas.addr_c_name) : ""
                    personalDatas.addr_a_name = personalDatas.addr_a_name ? replaceWithAsterisk(personalDatas.addr_a_name) : ''

                    $("#address").parents('td').html(personalDatas.addr_p_name + personalDatas.addr_c_name + personalDatas.addr_a_name + replaceWithAsterisk(personalDatas.address));
                    //$(".homeArea input[type='text']").parents('td').html(personalDatas.addr_p_name + personalDatas.addr_r_name + personalDatas.addr_a_name + personalDatas.address)

                    personalDatas.resid_p_name = personalDatas.resid_p_name ? replaceWithAsterisk(personalDatas.resid_p_name) : ''
                    personalDatas.resid_c_name = personalDatas.resid_c_name ? replaceWithAsterisk(personalDatas.resid_c_name) : ''
                    personalDatas.resid_a_name = personalDatas.resid_a_name ? replaceWithAsterisk(personalDatas.resid_a_name) : ''

                    $("#residence").parents('td').html(personalDatas.resid_p_name + personalDatas.resid_c_name + personalDatas.resid_a_name + replaceWithAsterisk(personalDatas.residence));

                    $("#payee").parents('td').html(personalDatas.payee ? personalDatas.payee : "未填写");
                    $("#account").parents('td').html((personalDatas.account ? personalDatas.account : "未填写") + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + (personalDatas.bank ? personalDatas.bank : "未填写")).removeClass('backBank');
                    if (personalDatas.house) {
                        $("#house > input[type='radio'][value=" + personalDatas.house + "]").prop('checked', true);
                        $("#house").html($("#house > input[type='radio']:checked").attr('va')).removeClass('PersonCol3');
                    }
                    else {
                        $("#house").html("未填写").removeClass('PersonCol3');
                    }
                    $("#monthRent").parents('td').html($("#house").html() + personalDatas.month_rent ? personalDatas.month_rent : "未填写").removeClass('PersonCol3');
                    $("#beginTime").parents('td').html(personalDatas.begin_time ? personalDatas.begin_time : "未填写");
                    $("#localTime").parents('td').html(personalDatas.local_time ? personalDatas.local_time : "未填写");
                    $("#homephone").parents('td').html(personalDatas.homephone ? personalDatas.homephone : "未填写");

                    //教育程度比较特殊
                    $("#education_list > option[value=" + personalDatas.education + "]").prop('selected', true);
                    var education = $("#education_list > option:selected").text();
                    $("#education_list").parents('td').html(education ? education : '未填写');

                    if (personalDatas.marry) {
                        $("#marry_list > option[value=" + personalDatas.marry + "]").prop('selected', true);
                    }
                    var marry = $("#marry_list > option:selected").text();
                    $("#marry_list").parents('td').html(marry ? marry : '未填写');
                    $("#child").parents('td').html(personalDatas.child ? personalDatas.child : "未填写");

                    $.each(feeDatas, function (index, item) {
                        if (item.fee) {
                            $("#count i[fee_id=" + item.fee_id + "] .money").html(item.fee);
                        }
                        else {
                            $("#count i[fee_id=" + item.fee_id + "] .money").html("0");
                        }
                    })

                    $.each(loanMethodDatas, function (i, e) {
                        $('#loanway input[loan_mehtod_id=' + e.loan_id + ']').parents('td').html($('input[loan_mehtod_id=' + e.loan_id + ']').parent('label').text())
                    })
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }, callError: function () {
                alert("请求失败")
            }
        });
    }

    function initFormSelect() {
        site.send({
            url: url.selectLoanTypeList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#loanType_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#loanType_content').html(html);
                    loanType = data.content;
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectApplyTermList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#applyTerm_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#applyTerm_content').html(html);
                    applyTerm = data.content;
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectRepanymentWayList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#repanymentWay_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#repanymentWay_content').html(html);
                    repaymentWay = data.content;
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectOrderSourceList,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#orderSource_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#orderSource_content').html(html);
                    orderSource = data.content;
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.selectLoanMethodList,
            data: {
                product_id: product_id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#loanMethod_content_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(data.content);
                    $('#loanMethod_content').append(html);
                    loanMethod = data.content
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })

        site.send({
            url: url.queryFeeRelation,
            data: {
                product_id: Constant.getAurlparam('product_id')
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var html = "";
                    $.each(data.content, function (i, e) {
                        var type = e.type == 1 ? '元' : '分';
                        html += '<i fee_id="' + e.fee_id + '"><em>' + e.fee_name + '：</em><em class="money"></em><em>' + type + '</em></i>';
                    })
                    $("#count").append(html);

                    //初始化checkbox点击功能
                    $.each($("#count input[type='checkbox']"), function (i, e) {
                        $(e).on('click', function () {
                            var c = $(e).parent('label').siblings('label')
                            if ($(e).is(':checked')) {
                                c.removeClass('isDisabled');
                                c.children('input[type="text"]').show();
                            }
                            else {
                                c.addClass('isDisabled');
                                c.children('input[type="text"]').hide();
                            }
                        })
                    })
                }
            }
        })
    }

    //制作分页
    var splitShortArr = function (longArr, row) {   // 将longArr 数组转换为2个数据为一组的小数组
        var convertData = [];
        for (var i = 0, len = longArr.length; i < len; i += row) {
            var item = longArr.slice(i, i + row);
            convertData.push(item);
        };
        return convertData;
    }


    //查询出要固定表单和自定义表单
    function queryForm(order_id) {
        site.send({
            url: url.queryProductForm,
            data: {
                product_id: product_id
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    //渲染客户自定义部分
                    if (data.content.personalPropertyCategorys) {
                        $.each(data.content.personalPropertyCategorys, function (index, item) {
                            $('#apply-PersonMess .form_myself').append('<div id="pcategorys' + index + '" style="overflow: hidden;"></div>');
                            $.each(item.personalPropertyDefines, function (index2, item2) {
                                $("#pcategorys" + index).append(item2.define_html);
                                $('#apply-PersonMess .component .controls').html('未填写');
                            })
                        })
                    }

                    //渲染产品自定义部分
                    if (data.content.productPropertyCategorys) {
                        $.each(data.content.productPropertyCategorys, function (index, item) {
                            $('#apply-message .form_myself').append('<div id="mcategorys' + index + '" style="overflow: hidden;"></div>');
                            $.each(item.personalPropertyDefines, function (index2, item2) {
                                $("#mcategorys" + index).append(item2.define_html);
                                $('#apply-message .component .controls').html('未填写');
                            })
                        })
                    }

                    if (order_id) {
                        fillFormData(order_id);
                    }
                }

                else {
                    Constant.fn.Message("F", data.msg)
                }
            }, callError: function () {

            }
        })
    }

    function queryNodeOperationRecordForm() {
        site.send({
            url: url.queryNodeOperationRecordForm,
            data: {
                order_id: getAurlparam('order_id')
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#operationRecord_list_tpl").html();
                    var template = Handlebars.compile(source);
                    data.loanType = loanType;
                    data.repaymentWay = repaymentWay;
                    data.applyTerm = applyTerm;
                    data.loanMethod = loanMethod;
                    data.orderSource = orderSource;

                    if (data.content.renderType === 2) {
                        var source2 = $("#process_line_tpl2").html();
                    } else {
                        var source2 = $("#process_line_tpl").html();
                    }

                    var template2 = Handlebars.compile(source2);
                    if (data.content.renderType === 2) {
                        $.each(data.content.nodeList, function (i, e) {
                            $.each(data.content.nodeRecordList, function (i2, e2) {
                                if (e.id == e2.node_id) {
                                    e.real_name = e2.real_name;
                                    e.type = e2.type;
                                    e.DURATION_ = e2.DURATION_;
                                    e.node_name = e2.node_name;
                                    e.username = e2.username;
                                    e.creat_time = e2.creat_time;
                                }
                            })
                        })
                    } else if (data.content.renderType === 1) {
                        $.each(data.content.flowList, function (i, e) {
                            $.each(data.content.nodeRecordList, function (i2, e2) {
                                if (e.node_id == e2.node_id) {
                                    e.real_name = e2.real_name;
                                    e.type = e2.type;
                                    e.creat_time = e2.creat_time;
                                }
                            })
                        })
                    }
                    var list2 = data.content;
                    list2.lastOne = data.content.nodeList[data.content.nodeList.length - 1];
                    console.log(list2);
                    var html2 = template2(list2)
                    $('#process_line').append(html2)

                    $('.exam-circle').on('mouseover', function () {
                        $(this).find('.exam-word').show();
                    }).on('mouseout', function () {
                        $(this).find('.exam-word').hide();
                    })

                    $('.call').on('click', function () {
                        var user_id = $(this).data('user_id')
                        site.send({
                            url: url.retrieverMessage,
                            data: {
                                order_id: order_id,
                                task_id: taskId,
                                user_id: user_id
                            },
                            callback: function (data) {
                                data = JSON.parse(data);
                                if (data.type === 1) {
                                    Constant.fn.Message("T", data.msg);
                                } else {
                                    Constant.fn.Message("F", data.msg);
                                }
                            }
                        })
                    })

                    site.send({
                        url: url.queryNodeOperationRecordValue,
                        data: {
                            order_id: getAurlparam('order_id')
                        },
                        callback: function (data2) {
                            var textarea;
                            data2 = JSON.parse(data2);
                            if (data2.type == 1) {

                                $.each(data.content.nodeRecordList, function (i, e) {
                                    $.each(data2.content.recordList, function (i2, e2) {
                                        if (e.id == e2[0].record_id) {
                                            e.datas = e2;
                                        }
                                    })
                                })

                                var html = template(data);
                                $('#apply-record').append(html);
                            }
                        }
                    })


                }
            }
        })
    }

    //$.when(initFormSelect()).then(queryNodeOperationRecordForm());

    $('#apply-PersonMess').show();

    $.when(initFormSelect()).then(queryForm(order_id));

    function queryImg(data){
        var source = $("#img_list_tpl").html();
        var template = Handlebars.compile(source);
        var html = template(data[currentPage]);
        $('#img_list').html(html);
        if(!data[currentPage][0]){
            $('#J-lbn').hide();
        }
        $('#J-lbcp').html(currentPage + 1);

        $('#img_list').viewer('destroy').viewer();
    }

    function queryTargetAttachment() {
        site.send({
            url: url.selectAttachmentTarget,
            data: {
                oid: order_id,
                attachId: '65'
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    a = splitShortArr(data.content[0].attachImg, 8);
                    pageCount = a.length;
                    $("#max-next").html(pageCount);
                    //console.log(a);
                    queryImg(a);
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            }
        })
    }

    //查询出借记录
    function queryLoanedRecord(frontData){
        site.send({
            url: url.Loanedecord,
            data: {
                oid: order_id
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    var source = $("#loanedRecord_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content;
                    var html = template(list);
                    $('#loanedRecord_list').html(html);
                    //分页
                    $('.loanedRecord-page-container').createPager({
                        current: frontData.pageNum,
                        total: data.content.total,
                        pageSize: data.content.pageSize,
                        needInput: false,
                        backFn: function (current) {
                            frontData.pageNum = current;
                            queryLoanedRecord(frontData);
                        }
                    })
                } else {
                    Constant.fn.Message("F", data.msg);
                }
            },
            callError: function () {
                alert("error")
            }
        })
    }

    $('.btn-next,.borrow-images-next').on('click',function(){
        currentPage += 1;
        if(currentPage > pageCount - 1){
            currentPage = 0;
        }
        queryImg(a);
    })

    $('.btn-prev,.borrow-images-prev').on('click',function(){
        currentPage -= 1;
        if(currentPage < 0){
            currentPage = pageCount -1;
        }
        queryImg(a);
    })

    //tab 切换
    $('.public-PoBefore-nav li a').on('click', function () {
        var params = $(this).data('type');
        if (params == 'reimbursement' || params == 'PersonMess' || params == 'message' || params == 'dataList' || params == 'record' || params == 'loanedRecord') {
            //Reimbursement=还款明细
            //message=借款信息
            //personMess=借款人資料
            //dataList=資料清單
            //record=审批记录
            //切换菜单
            $('.public-PoBefore-nav li a').removeClass('activePublic');
            $(this).addClass('activePublic');

            //切换内容
            $("[id^=apply-]").hide();
            $('#apply-' + params).show();
        }
        if (params == 'dataList') {
            queryTargetAttachment();
        }
        if (params == 'loanedRecord'){
            queryLoanedRecord(frontData);
        }
    });

    /*var detail = function () {
        Constant.initHandlebars(Handlebars)
        var url = {
            queryOrderAndProduct: "manager/queryOrderInfos.do",
            queryProductForm: "manager/selectProductFormCustom.do",
            selectEducation: "manager/selectEducation.do",
            selectLoanTypeList: "manager/selectLoanTypeList.do",
            selectApplyTermList: "manager/selectApplyTermList.do",
            selectOrderSourceList: "manager/selectOrderSourceList.do",
            selectRepanymentWayList: "manager/selectRepanymentWayList.do",
            selectLoanMethodList: "manager/queryLoanDefineByProductId.do",
            queryFeeRelation: "manager/queryFeeRelationByProductId.do",
            selectAttachmentList: "manager/selectAttachmentAll.do",
            queryNodeOperationRecordForm: "manager/queryNodeOperationRecordForm.do",
            queryNodeOperationRecordValue: "manager/queryNodeOperationRecordValue.do",
            selectMarry: "manager/selectMarry.do",
            queryPlan: "manager/queryPlan.do",
            downloadPicturesZip: "manager/downloadPicturesZip.do",
            ajaxqueryRegion: localStorage.getItem('host') + "manager/ajaxqueryRegion.do",
            getActivitiProccessImage: "manager/getActivitiProccessImage.do",

            //关于审批的所有接口
            queryLoanDefineByProductId: "manager/queryLoanDefineByProductId.do",
            queryAdminRoleByRole: "manager/queryAdminRoleByRoleId.do",
            roamTask: "manager/roamTask.do",
            insertAttachment: "manager/insertAttachment.do",
            saveNodefromInfos: "manager/saveNodefromInfos.do",
            queryNodeFromInfoAllByONid: "manager/queryNodeFromInfoAllByONid.do",
            retrieverMessage: "manager/retrieverMessage.do",
        }




        var atchId;

        //var taskId = getAurlparam('task_id');
        //var node_id = getAurlparam('node_id');
        //var s_id = getAurlparam('s_id');
        var approvalType;
        var loanType, repaymentWay, applyTerm, loanMethod, orderSource;

        //用来判断是否是第一次点击,借款人信息或借款信息第一次点击才调接口
        var first = true;


        //特殊处理
        $.when(initFormSelect()).then(queryForm(order_id));

        //还款明细
        if ($("#reimbursement_list_tpl").html()) {
            site.send({
                url: url.queryPlan,
                data: {
                    oid: order_id
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == '1') {
                        var source = $("#reimbursement_list_tpl").html();
                        var template = Handlebars.compile(source);
                        var order = data.content.order;

                        $.when(
                            $.ajax({
                                url: url.ajaxqueryRegion,
                                data: {
                                    parentId: 0
                                },
                                crossDomain: true,
                                xhrFields: {
                                    withCredentials: true
                                }
                            }), $.ajax({
                                url: url.ajaxqueryRegion,
                                data: {
                                    parentId: order.first_party_province
                                },
                                crossDomain: true,
                                xhrFields: {
                                    withCredentials: true
                                }
                            }), $.ajax({
                                url: url.ajaxqueryRegion,
                                data: {
                                    parentId: order.first_party_city
                                },
                                crossDomain: true,
                                xhrFields: {
                                    withCredentials: true
                                }
                            })
                        ).done(function (data1, data2, data3) {
                            if (data1[0] == 'noRole') {
                                Constant.fn.Message("F", "noRole");
                                return;
                            }
                            data1 = JSON.parse(data1[0]);
                            $.each(data1, function (i, e) {
                                if (order.first_party_province == e.ID) {
                                    data.content.order.first_party_province = e.name;
                                }
                            })
                            data2 = JSON.parse(data2[0]);
                            $.each(data2, function (i, e) {
                                if (order.first_party_city == e.ID) {
                                    data.content.order.first_party_city = e.name;
                                }
                            })
                            data3 = JSON.parse(data3[0]);
                            $.each(data3, function (i, e) {
                                if (order.first_party_area == e.ID) {
                                    data.content.order.first_party_area = e.name;
                                }
                            })
                            var html = template(data.content);
                            $('#apply-reimbursement').append(html);
                        })
                    }
                }
            })
        }

        $("[id^=apply]").hide();
        $("#apply-" + $('.public-PoBefore-nav li:eq(0) a').data('type')).show();

        if (s_id == '0') {
            $('.record').hide();
            $('#apply-record').hide();
            $('.public-PoBefore-nav li:eq(1) a').addClass('activePublic');
            $('#apply-PersonMess').show();
            $.when(initFormSelect()).then(queryForm(order_id));
            first = false;
            $('.public-bgBotBtn').show();

            //待提交状态下的提交，也就是在第一步的时候
            $("#submit").on('click', function () {
                $('.special_processForm_winBox').toggle();
                specialQueryRole(order_id);
            })

        } else {
            $.when(initFormSelect()).then(queryNodeOperationRecordForm());

            console.log(getAurlparam('audit_status'))
            if (getAurlparam('t') == 0 && getAurlparam('isSubmit') != 'yes') {
                $('.public-bgBotBtn').show();
            }
            //后面流程的提交，在第一步之后，会有流程表单
            $("#submit").on('click', function () {
                $('.processForm_winBox').toggle();
                queryNodeForm(order_id, node_id, product_id)
            })
        }


        function queryNodeOperationRecordForm() {
            site.send({
                url: url.queryNodeOperationRecordForm,
                data: {
                    order_id: getAurlparam('order_id')
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#operationRecord_list_tpl").html();
                        var template = Handlebars.compile(source);
                        data.loanType = loanType;
                        data.repaymentWay = repaymentWay;
                        data.applyTerm = applyTerm;
                        data.loanMethod = loanMethod;
                        data.orderSource = orderSource;

                        if (data.content.renderType === 2) {
                            var source2 = $("#process_line_tpl2").html();
                        } else {
                            var source2 = $("#process_line_tpl").html();
                        }

                        var template2 = Handlebars.compile(source2);
                        if (data.content.renderType === 2) {
                            $.each(data.content.nodeList, function (i, e) {
                                $.each(data.content.nodeRecordList, function (i2, e2) {
                                    if (e.id == e2.node_id) {
                                        e.real_name = e2.real_name;
                                        e.type = e2.type;
                                        e.DURATION_ = e2.DURATION_;
                                        e.node_name = e2.node_name;
                                        e.username = e2.username;
                                        e.creat_time = e2.creat_time;
                                    }
                                })
                            })
                        } else if (data.content.renderType === 1) {
                            $.each(data.content.flowList, function (i, e) {
                                $.each(data.content.nodeRecordList, function (i2, e2) {
                                    if (e.node_id == e2.node_id) {
                                        e.real_name = e2.real_name;
                                        e.type = e2.type;
                                        e.creat_time = e2.creat_time;
                                    }
                                })
                            })
                        }
                        var list2 = data.content;
                        list2.lastOne = data.content.nodeList[data.content.nodeList.length - 1];
                        console.log(list2);
                        var html2 = template2(list2)
                        $('#process_line').append(html2)

                        $('.exam-circle').on('mouseover', function () {
                            $(this).find('.exam-word').show();
                        }).on('mouseout', function () {
                            $(this).find('.exam-word').hide();
                        })

                        $('.call').on('click', function () {
                            var user_id = $(this).data('user_id')
                            site.send({
                                url: url.retrieverMessage,
                                data: {
                                    order_id: order_id,
                                    task_id: taskId,
                                    user_id: user_id
                                },
                                callback: function (data) {
                                    data = JSON.parse(data);
                                    if (data.type === 1) {
                                        Constant.fn.Message("T", data.msg);
                                    } else {
                                        Constant.fn.Message("F", data.msg);
                                    }
                                }
                            })
                        })

                        site.send({
                            url: url.queryNodeOperationRecordValue,
                            data: {
                                order_id: getAurlparam('order_id')
                            },
                            callback: function (data2) {
                                var textarea;
                                data2 = JSON.parse(data2);
                                if (data2.type == 1) {

                                    $.each(data.content.nodeRecordList, function (i, e) {
                                        $.each(data2.content.recordList, function (i2, e2) {
                                            if (e.id == e2[0].record_id) {
                                                e.datas = e2;
                                            }
                                        })
                                    })

                                    var html = template(data);
                                    $('#apply-record').append(html);
                                }
                            }
                        })


                    }
                }
            })
        }

        //tab 切换
        $('.public-PoBefore-nav li a').on('click', function () {
            var params = $(this).data('type');
            if (params == 'reimbursement' || params == 'PersonMess' || params == 'message' || params == 'dataList' || params == 'record') {
                //Reimbursement=还款明细
                //message=借款信息
                //personMess=借款人資料
                //dataList=資料清單
                //record=审批记录
                //切换菜单
                $('.public-PoBefore-nav li a').removeClass('activePublic');
                $(this).addClass('activePublic');

                //切换内容
                $("[id^=apply]").hide();
                $('#apply-' + params).show();
            }
        });


        //tab切换是只请求一次接口
        $('.public-PoBefore-nav li a').one('click', function () {
            var params = $(this).data('type');
            if (params == 'reimbursement' || params == 'PersonMess' || params == 'message' || params == 'dataList' || params == 'record') {
                //Reimbursement=还款明细
                //message=借款信息
                //personMess=借款人資料
                //dataList=資料清單
                //record=审批记录
                //切换菜单
            }
            if (params == 'PersonMess' || params == 'message') {
                if (first) {
                    queryForm(order_id);
                }
                first = false;
            }

            if (params == 'dataList') {
                selectAttachment();
            }
        });

        function initFormSelect() {
            site.send({
                url: url.selectLoanTypeList,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#loanType_content_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('#loanType_content').html(html);
                        loanType = data.content;
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }
            })

            site.send({
                url: url.selectApplyTermList,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#applyTerm_content_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('#applyTerm_content').html(html);
                        applyTerm = data.content;
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }
            })

            site.send({
                url: url.selectRepanymentWayList,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#repanymentWay_content_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('#repanymentWay_content').html(html);
                        repaymentWay = data.content;
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }
            })

            site.send({
                url: url.selectOrderSourceList,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#orderSource_content_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('#orderSource_content').html(html);
                        orderSource = data.content;
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }
            })

            site.send({
                url: url.selectLoanMethodList,
                data: {
                    product_id: product_id
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#loanMethod_content_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('#loanMethod_content').append(html);
                        loanMethod = data.content
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }
            })

            site.send({
                url: url.queryFeeRelation,
                data: {
                    product_id: Constant.getAurlparam('product_id')
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var html = "";
                        $.each(data.content, function (i, e) {
                            var type = e.type == 1 ? '元' : '分';
                            html += '<i fee_id="' + e.fee_id + '"><em>' + e.fee_name + '：</em><em class="money"></em><em>' + type + '</em></i>';
                        })
                        $("#count").append(html);

                        //初始化checkbox点击功能
                        $.each($("#count input[type='checkbox']"), function (i, e) {
                            $(e).on('click', function () {
                                var c = $(e).parent('label').siblings('label')
                                if ($(e).is(':checked')) {
                                    c.removeClass('isDisabled');
                                    c.children('input[type="text"]').show();
                                }
                                else {
                                    c.addClass('isDisabled');
                                    c.children('input[type="text"]').hide();
                                }
                            })
                        })
                    }
                }
            })
        }

        //获取教育程度接口
        site.send({
            url: url.selectEducation,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#education_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content
                    var html = template(list)
                    $('#education_list').append(html)
                }
            }
        })

        //获取婚姻状况
        site.send({
            url: url.selectMarry,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == 1) {
                    var source = $("#marry_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content
                    var html = template(list)
                    $('#marry_list').append(html)
                }
            }
        })


        //查询出要固定表单和自定义表单
        function queryForm(order_id) {
            site.send({
                url: url.queryProductForm,
                data: {
                    product_id: product_id
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        //渲染客户自定义部分
                        if (data.content.personalPropertyCategorys) {
                            $.each(data.content.personalPropertyCategorys, function (index, item) {
                                $('#apply-PersonMess .form_myself').append('<div id="pcategorys' + index + '" style="overflow: hidden;"></div>');
                                $.each(item.personalPropertyDefines, function (index2, item2) {
                                    $("#pcategorys" + index).append(item2.define_html);
                                    $('#apply-PersonMess .component .controls').html('未填写');
                                })
                            })
                        }

                        //渲染产品自定义部分
                        if (data.content.productPropertyCategorys) {
                            $.each(data.content.productPropertyCategorys, function (index, item) {
                                $('#apply-message .form_myself').append('<div id="mcategorys' + index + '" style="overflow: hidden;"></div>');
                                $.each(item.personalPropertyDefines, function (index2, item2) {
                                    $("#mcategorys" + index).append(item2.define_html);
                                    $('#apply-message .component .controls').html('未填写');
                                })
                            })
                        }

                        if (order_id) {
                            fillFormData(order_id);
                        }
                    }

                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }, callError: function () {

                }
            })
        }

        //填充页面数据
        function fillFormData() {
            site.send({
                url: url.queryOrderAndProduct,
                data: {
                    order_id: getAurlparam('order_id')
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {

                        var orderDatas = data.content.orderDatas;
                        var productRealDatas = data.content.productRealDatas;
                        var feeDatas = data.content.feeDatas;
                        var personalDatas = data.content.personalDatas;
                        var personalRealDatas = data.content.personalRealDatas;
                        var loanMethodDatas = data.content.loanMethodDatas;

                        $("#apply_money").parents('td').html("￥" + Constant.tplHelper.AMOUNT_FORMAT(orderDatas.apply_money));
                        $('#loanType_content').parents('td').html($('#loanType_content option[data-id=' + orderDatas.lt_id + ']').text());
                        $('#repanymentWay_content').parents('td').html($('#repanymentWay_content option[data-id=' + orderDatas.repayment_way + ']').text());
                        if(orderDatas.at_id){
                            $('#applyTerm_content').parents('td').html($('#applyTerm_content option[data-id=' + orderDatas.at_id + ']').text());
                        }
                        if(orderDatas.at_id){
                            $('#apply_day').parents('td').html(orderDatas.at_id + '天');
                        }

                        //还款方式为按天收息的特殊判断
                        if(orderDatas.repayment_way == '4'){
                            $(".applyTrem").hide()
                            $(".applyDay").show();
                        }else{
                            $(".applyTrem").show();
                            $(".applyDay").hide();
                        }

                        $('#loanMethod_content').parents('td').html($('#loanMethod_content input[value=' + orderDatas.loan_way + ']').parent('label').text());
                        $('#orderSource_content').parents('td').html($('#orderSource_content option[data-id=' + orderDatas.os_id + ']').text() ? $('option[data-id=' + orderDatas.os_id + ']').text() : "未填写");
                        //$('#count span .money').html(orderDatas.interest);
                        $('.public-content-Po').html(orderDatas.loan_number);

                        $("#count span").html('<em>利率：' + orderDatas.interest + '分</em>');

                        $.each(productRealDatas, function (index, item) {
                            var type = item.type
                            $('#apply-message .component[id=' + item.property_id + ']').attr('op_id', item.id);
                            if (item.value) {
                                $('#apply-message .component[id=' + item.property_id + '] .controls').html(item.value);
                            }
                            else {
                                $('#apply-message .component[id=' + item.property_id + '] .controls').html('未填写');
                            }
                        })

                        $.each(personalRealDatas, function (index, item) {
                            var type = item.type
                            $('#apply-PersonMess .component[id=' + item.property_id + ']').attr('op_id', item.id);
                            if (item.value) {
                                $('#apply-PersonMess .component[id=' + item.property_id + '] .controls').html(item.value);
                            }
                            else {
                                $('#apply-PersonMess .component[id=' + item.property_id + '] .controls').html('未填写');
                            }
                        })

                        //客户固定字段渲染
                        $.each(personalDatas.borrowerDatas, function (i, e) {
                            var a = i + 1;
                            if (i == 0) {
                                $(".personMess:first .realName").parents('td').html("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style='min-width: 68px; display: inline-block'>" + e.real_name + "</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + e.id_card + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + e.birth_date + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + e.cellphone + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + (e.sex === 1 ? '男' : '女'));
                            }
                            else {
                                $(".personMess:last").after('<tr i="' + i + '" class="personMess ng-scope">\n' +
                                    '            <td class="ng-binding"><span>*</span>借款人' + a + '</td>\n' +
                                    '            <td colspan="7" style="text-align: left">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="min-width: 68px; display: inline-block">' + e.real_name + '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + e.id_card + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + e.birth_date + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + e.cellphone + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + (e.sex === 1 ? '男' : '女') + '</td>\n' +
                                    '        </tr>')
                                $('tr[i=' + i + '] input[value=' + e.sex + ']').parent('.sex-radio').addClass('is-checked');
                            }
                        })
                        personalDatas.addr_p_name = personalDatas.addr_p_name ? personalDatas.addr_p_name : ""
                        personalDatas.addr_c_name = personalDatas.addr_c_name ? personalDatas.addr_c_name : ""
                        personalDatas.addr_a_name = personalDatas.addr_a_name ? personalDatas.addr_a_name : ''

                        $("#address").parents('td').html(personalDatas.addr_p_name + personalDatas.addr_c_name + personalDatas.addr_a_name + personalDatas.address);
                        //$(".homeArea input[type='text']").parents('td').html(personalDatas.addr_p_name + personalDatas.addr_r_name + personalDatas.addr_a_name + personalDatas.address)

                        personalDatas.resid_p_name = personalDatas.resid_p_name ? personalDatas.resid_p_name : ''
                        personalDatas.resid_c_name = personalDatas.resid_c_name ? personalDatas.resid_c_name : ''
                        personalDatas.resid_a_name = personalDatas.resid_a_name ? personalDatas.resid_a_name : ''

                        $("#residence").parents('td').html(personalDatas.resid_p_name + personalDatas.resid_c_name + personalDatas.resid_a_name + personalDatas.residence);

                        $("#payee").parents('td').html(personalDatas.payee ? personalDatas.payee : "未填写");
                        $("#account").parents('td').html((personalDatas.account ? personalDatas.account : "未填写") + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + (personalDatas.bank ? personalDatas.bank : "未填写")).removeClass('backBank');
                        if (personalDatas.house) {
                            $("#house > input[type='radio'][value=" + personalDatas.house + "]").prop('checked', true);
                            $("#house").html($("#house > input[type='radio']:checked").attr('va')).removeClass('PersonCol3');
                        }
                        else {
                            $("#house").html("未填写").removeClass('PersonCol3');
                        }
                        $("#monthRent").parents('td').html($("#house").html() + personalDatas.month_rent ? personalDatas.month_rent : "未填写").removeClass('PersonCol3');
                        $("#beginTime").parents('td').html(personalDatas.begin_time ? personalDatas.begin_time : "未填写");
                        $("#localTime").parents('td').html(personalDatas.local_time ? personalDatas.local_time : "未填写");
                        $("#homephone").parents('td').html(personalDatas.homephone ? personalDatas.homephone : "未填写");

                        //教育程度比较特殊
                        $("#education_list > option[value=" + personalDatas.education + "]").prop('selected', true);
                        var education = $("#education_list > option:selected").text();
                        $("#education_list").parents('td').html(education ? education : '未填写');

                        if (personalDatas.marry) {
                            $("#marry_list > option[value=" + personalDatas.marry + "]").prop('selected', true);
                        }
                        var marry = $("#marry_list > option:selected").text();
                        $("#marry_list").parents('td').html(marry ? marry : '未填写');
                        $("#child").parents('td').html(personalDatas.child ? personalDatas.child : "未填写");

                        $.each(feeDatas, function (index, item) {
                            if (item.fee) {
                                $("#count i[fee_id=" + item.fee_id + "] .money").html(item.fee);
                            }
                            else {
                                $("#count i[fee_id=" + item.fee_id + "] .money").html("0");
                            }
                        })

                        $.each(loanMethodDatas, function (i, e) {
                            $('#loanway input[loan_mehtod_id=' + e.loan_id + ']').parents('td').html($('input[loan_mehtod_id=' + e.loan_id + ']').parent('label').text())
                        })
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }, callError: function () {
                    alert("请求失败")
                }
            });
        }


        //查出已上传图片
        function selectAttachment(id) {
            var data = {
                oid: order_id,
                product_id: product_id,
            }
            if (id) {
                data.attach_id = id;
            }
            site.send({
                url: url.selectAttachmentList,
                data: data,
                callback: function (data) {
                    data = JSON.parse(data)
                    if (data.type == 1) {
                        if (data.content) {
                            $('.result').html(data.content.length);
                        }
                        var source = $("#image_list_tpl").html();
                        var template = Handlebars.compile(source);
                        var list = data.content
                        $.each(list, function (i, e) {
                            e.img = [];
                            e.file = [];
                            if (e.attachImg && e.attachImg.length) {
                                $.each(e.attachImg, function (ii, ee) {
                                    if(ee){
                                        var postFix = Constant.fn.getFileType(ee);
                                        if (postFix === 'jpg' || postFix === 'png' || postFix === 'jpeg') {
                                            e.img.push(ee);
                                        } else {
                                            e.file.push({
                                                href: ee,
                                                type: postFix,
                                                name: Constant.fn.getFileName(ee)
                                            });
                                        }
                                    }else {

                                    }
                                })
                            }
                            e.imgLength = e.img.length;
                            e.fileLength = e.file.length;
                        })
                        var html = template(list)
                        $('#image_list').html(html)

                        if (!id) {
                            var source = $("#attachmentType_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data.content
                            var html = template(list)
                            $('#attachmentType').html(html)
                        }

                        //var rorate = 2;
                        $('[id^="gallery"]').viewer('destroy').viewer();
                        $(".more").on('click', function () {
                            if ($(this).data('rotate') % 2 === 0) {
                                $(this).css('transform', 'rotate(180deg)');
                            } else {
                                $(this).css('transform', 'rotate(0deg)');
                            }
                            $(this).data('rotate', $(this).data('rotate') + 1);
                            $(this).parents('[id^="gallery"]').find('li:gt(2)').toggle();
                        })
                        $(".fileMore").on('click', function () {
                            if ($(this).data('rotate') % 2 === 0) {
                                $(this).css('transform', 'rotate(180deg)');
                            } else {
                                $(this).css('transform', 'rotate(0deg)');
                            }
                            $(this).data('rotate', $(this).data('rotate') + 1);
                            $(this).parents('[id^="fileGallery"]').find('a:gt(2)').toggle();
                        })
                    }
                    else {
                        Constant.fn.Message("I", data.msg)
                    }
                }
            })
        }

        $(".search").on('click', function () {
            selectAttachment($("#attachmentType").val())
        })

        //下载合同方法
        function downloadFile(src) {
            var $a = document.createElement('a');
            $a.setAttribute("href", src);
            $a.setAttribute("download", "");
            var evObj = document.createEvent('MouseEvents');
            evObj.initMouseEvent('click', true, true, document.defaultView, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
            $a.dispatchEvent(evObj);
            window.close();
        }

        $("#downLoad").on('click', function () {
            var ids = "";
            var data = {
                oid: order_id
            }
            if ($("#attachmentType").val()) {
                data.attach_id = $("#attachmentType").val();
            }
            $.each($('[id^="gallery"]'), function (i, e) {
                ids += $(this).attr('allid') + ',';
            })

            ids = ids.substring(0, ids.length - 1);
            data.ids = ids;

            site.send({
                url: url.downloadPicturesZip,
                data: data,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == '1') {
                        window.open(data.content);
                    }
                    else {
                        Constant.fn.Message("F", data.msg);
                    }
                },
                callError: function (e) {
                    Constant.fn.Message("F", e);
                }
            })
        })

        /!******************在查看订单加入流转功能***************!/
        //查询出角色
        function specialQueryRole(order_id) {
            site.send({
                url: url.queryAdminRoleByRole,
                //async:false
                data: {
                    order_id: order_id
                },
                callback: function (data) {
                    data = JSON.parse(data)
                    if (data.type == 1) {
                        var source = $("#special_role_list_tpl").html();
                        var template = Handlebars.compile(source);
                        var list = data.content
                        var html = template(list)
                        $('.special_processForm_winBox .assBox2').html(html)

                        //下拉框选中获取值
                        $(".special_processForm_winBox #special_role_select").on('change', function () {
                            userId = $(this).find("option:selected").val();
                        })
                    }
                }
            })
        }

        //节点表单流转查询出角色
        function queryRole(order_id) {
            site.send({
                url: url.queryAdminRoleByRole,
                data: {
                    order_id: order_id
                },
                callback: function (data) {
                    data = JSON.parse(data)
                    if (data.type == 1) {
                        var source = $("#role_list_tpl").html();
                        var template = Handlebars.compile(source);
                        var list = data.content
                        var html = template(list)
                        $('.role_list').append(html)

                        if (data.content) {
                            approvalType = data.content.approvalType;
                        }

                        //下拉框选中获取值
                        $("#role_select").on('change', function () {
                            userId = $(this).find("option:selected").val();
                            if (approvalType == '2') {
                                var flag = true;
                                if ($(this).val()) {
                                    var userName = $(this).find("option:selected").text();
                                    $('.chooseRole').show();
                                    if (!$('.choose-per').length) {
                                        $('.chooseRole .selPers').append('<span data-userid= ' + userId + ' class="choose-per"><span class="choose-perName">' + userName + '</span><span class="removeRole" style="cursor: pointer;">×</span></span>');
                                    }
                                    else {
                                        $.each($('.choose-per'), function (i, e) {
                                            //console.log()
                                            console.log($(e).data('userid'));
                                            if (userId == $(e).data('userid')) {
                                                //$('.chooseRole .selPers').append('<span data-userid= ' + userId + ' class="choose-per"><span class="choose-perName">' + userName + '</span><span class="removeRole" style="cursor: pointer;">×</span></span>');
                                                flag = false;
                                            }
                                        })
                                        if (flag) {
                                            $('.chooseRole .selPers').append('<span data-userid= ' + userId + ' class="choose-per"><span class="choose-perName">' + userName + '</span><span class="removeRole" style="cursor: pointer;">×</span></span>');
                                        }
                                    }
                                }
                                $('.removeRole').unbind().on('click', function () {
                                    $(this).parents('.choose-per').remove();
                                    console.log($(this).parents('td'));
                                    if ($('.selPers').find('.choose-per').length == 0) {
                                        $(".chooseRole").hide();
                                        $("#role_select").val('');
                                    }
                                })
                            }
                        })
                    }
                    else {
                        Constant.fn.Message('F', data.msg);
                        $('.processForm_winBox').toggle();
                    }
                }
            })
        }

        //初始化节点表单固定字段的选项
        function initformSelect(content) {
            site.send({
                url: url.selectLoanTypeList,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#loanType_content_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('.processForm_winBox #loanType_content').html(html);

                        var orderInfos = content.orderInfos;
                        $.each(orderInfos, function (i, e) {
                            if (e.fixed_key == "lt_id") {
                                if (e.is_edit == 1) {
                                    $(".processForm_winBox #loanType_content option[data-id=" + e.real_data + "]").attr("selected", true)
                                }
                                else {
                                    $(".processForm_winBox #loanType_content").parents('td').html($(".processForm_winBox #loanType_content option[data-id=" + e.real_data + "]").text());
                                }
                            }
                        })
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }
            })

            site.send({
                url: url.selectApplyTermList,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#applyTerm_content_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('.processForm_winBox #applyTerm_content').html(html);
                        var source = $("#at_id_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('#at_id').html(html);


                        var orderInfos = content.orderInfos;
                        $.each(orderInfos, function (i, e) {
                            if (e.fixed_key == "at_id") {
                                if (e.is_edit == 1) {
                                    $(".processForm_winBox #applyTerm_content option[data-id=" + e.real_data + "]").attr("selected", true)
                                }
                                else {
                                    $(".processForm_winBox #applyTerm_content").parents('td').html($(".processForm_winBox #applyTerm_content option[data-id=" + e.real_data + "]").text());
                                }
                            }
                        })
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }
            })

            site.send({
                url: url.selectRepanymentWayList,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#repanymentWay_content_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('.processForm_winBox #repanymentWay_content').html(html);

                        var orderInfos = content.orderInfos;
                        $.each(orderInfos, function (i, e) {
                            if (e.fixed_key == "repayment_way") {
                                if (e.is_edit == 1) {
                                    $(".processForm_winBox #repanymentWay_content option[data-id=" + e.real_data + "]").attr("selected", true)
                                }
                                else {
                                    var real_data = $(".processForm_winBox #repanymentWay_content option[data-id=" + e.real_data + "]").text()
                                    real_data ? $(".processForm_winBox #repanymentWay_content").parents('td').html(real_data) : "未填写";
                                }
                            }
                        })
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }
            })

            site.send({
                url: url.selectOrderSourceList,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#orderSource_content_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('.processForm_winBox #orderSource_content').html(html);

                        var orderInfos = content.orderInfos;
                        $.each(orderInfos, function (i, e) {
                            if (e.fixed_key == "os_id") {
                                if (e.is_edit == 1) {
                                    $(".processForm_winBox #orderSource_content option[data-id=" + e.real_data + "]").attr("selected", true)
                                }
                                else {
                                    var real_data = $(".processForm_winBox #orderSource_content option[data-id=" + e.real_data + "]").text()
                                    real_data ? $(".processForm_winBox #orderSource_content").parents('td').html(real_data) : "未填写";
                                }
                            }
                            if (e.fixed_key == "apply_money") {
                                if (e.is_edit == 1) {
                                    $(".processForm_winBox #apply_money").val(e.real_data);
                                }
                                else {
                                    $(".processForm_winBox #apply_money").parents('td').html(e.real_data + "元");
                                }
                            }
                        })
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }
            })

            site.send({
                url: url.queryLoanDefineByProductId,
                data: {
                    product_id: product_id
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        var source = $("#loanMethod_content_tpl").html();
                        var template = Handlebars.compile(source);
                        var html = template(data.content);
                        $('.processForm_winBox #loanMethod_content').append(html);

                        var orderInfos = content.orderInfos;
                        $.each(orderInfos, function (i, e) {
                            if (e.fixed_key == "loan_way") {
                                if (e.is_edit == 1) {
                                    $(".processForm_winBox #loanMethod_content input[value=" + e.real_data + "]").prop("checked", true);
                                }
                                else {
                                    $(".processForm_winBox #loanMethod_content input[value=" + e.real_data + "]").prop("checked", true);
                                    $(".processForm_winBox #loanMethod_content").parents('tr').html($('.processForm_winBox #loanMethod_content input[type="radio"]:checked').text());
                                }
                            }
                        })
                    }
                    else {
                        Constant.fn.Message("F", data.msg)
                    }
                }
            })
        }


        //流转查询出表单
        function queryNodeForm(order_id, node_id, product_id) {
            site.send({
                url: url.queryNodeFromInfoAllByONid,
                data: {
                    node_id: node_id,
                    order_id: order_id,
                    product_id: product_id
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        //handlebars模板引擎
                        var source = $("#form_list_tpl").html()
                        var template = Handlebars.compile(source)
                        var content = data.content
                        var html = template(content)
                        $('.formBox .approve').before(html)

                        $('#apply_money').on({
                            'focus': function () {
                                $(this).val(Constant.fn.toNum($(this).val()));
                            },
                            'blur': function () {
                                $(this).val(Constant.fn.toRMB($(this).val()));
                            }
                        })

                        $('.processForm_winBox .winBox1').viewer('destroy').viewer();
                        Constant.fn.initScroll();

                        OSS_IMAGE_INIT(order_id, node_id);

                        //删除单张图片
                        $('.delSingleAttach').unbind().on('click', function (e) {
                            e.stopPropagation();
                            e.preventDefault();
                            $(this).parents('li').remove();
                            Constant.fn.initScroll();
                        })

                        //渲染真实数据
                        initformSelect(content);
                    }
                }
            })
        }

        //流转
        function specialRoamTask(userId, remark) {
            var data = {
                taskId: taskId,
                userId: userId,
                orderId: order_id,
                remark: remark,
                type: '1'
            }
            site.send({
                url: url.roamTask,
                data: data,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        $('.special_processForm_winBox').toggle();
                        Constant.fn.Message('T', data.msg);
                        history.go(-1);
                    } else {
                        Constant.fn.Message("F", data.msg)
                    }
                },
                callError: function () {

                }
            })
        }

        $("#specialRoamTask").on('click', function () {
            //验证是否选择角色
            var userId = $("#special_role_select option:selected").val();
            var remark = $(".approveRemark").val();
            if (!userId) {
                Constant.fn.Message('I', '请选择审批角色');
                return;
            }
            if (!remark) {
                Constant.fn.Message('I', '请输入备注');
                return;
            }
            ;
            specialRoamTask(userId, remark);
        })

        //流转
        function roamTask(userId, type, remark) {
            //console.log(flag);
            var data = {
                taskId: taskId,
                userId: userId,
                orderId: order_id,
                remark: remark,
                type: type
            }
            site.send({
                url: url.roamTask,
                data: data,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        $('.processForm_winBox').toggle();
                        Constant.fn.Message('T', data.msg);
                        history.go(-1);
                    } else {
                        Constant.fn.Message("F", data.msg)
                    }
                },
                callError: function () {

                }
            })
        }

        //点击流转保存图片
        function saveImg(userId, type, remark) {
            var ajaxLength = $('.processForm_winBox [attachid]').length;
            if (ajaxLength) {
                $.each($('.processForm_winBox [attachid]'), function (i, e) {
                    var data = {
                        attachImg: "",
                        attachName: $(e).attr('attachname'),
                        attachId: $(e).attr('attachid'),
                        oid: order_id,
                        //oid: 1,
                        productId: product_id,
                        nodeId: node_id,
                        //nodeId: 2,
                        order_num: order_num,
                        //s_id: '1'
                        type: $(e).parents('td').find('input[type="radio"]:checked').val()
                    }

                    if($(e).attr('attachid') == '65'){
                        data.is_target = 1;
                    }else{
                        data.is_target = -1;
                    }

                    var attachImg = [];
                    $.each($(e).find('li'), function (ii, ee) {
                        attachImg.push($(ee).attr('href'));
                    })

                    if (attachImg.length) {
                        data.attachImg = JSON.stringify(attachImg)
                    }

                    site.send({
                        url: url.insertAttachment,
                        data: data,
                        callback: function (data) {
                            data = JSON.parse(data)
                            if (data.type == 1) {
                                ajaxLength -= 1;
                                if (ajaxLength === 0) {
                                    roamTask(userId, type, remark);
                                }
                            }
                        }
                    })
                })
            } else {
                roamTask(userId, type, remark);
            }
        }

        function saveNodefromInfos() {
            var productInfos = new Array();
            //获取产品自定义真实数据信息
            var td = $(".productInfos").find('td[property_id]');
            $.each(td, function (i, e) {
                var productForm = $(e).find('[productForm]')
                if (productForm.attr('productForm') == 'text') {
                    var obj = {
                        property_id: $(e).attr('property_id'),
                        name: $(e).attr('name'),
                        fixed_name: $(e).attr('name'),
                        required: $(e).attr('require'),
                        order_id: order_id,
                        value: productForm.val(),
                        record_value: productForm.val()
                    }
                }
                if (productForm.attr('productForm') == 'select') {
                    var obj = {
                        property_id: $(e).attr('property_id'),
                        name: $(e).attr('name'),
                        fixed_name: $(e).attr('name'),
                        required: $(e).attr('require'),
                        order_id: order_id,
                        content_ids: productForm.find('option:selected').val(),
                        value: productForm.find('option:selected').val() ? productForm.find('option:selected').text() : '',
                        record_value: productForm.find('option:selected').val() ? productForm.find('option:selected').text() : ''
                    }
                }
                if (productForm.attr('productForm') == 'radio') {
                    var content_ids = "";
                    var value = "";
                    var record_value = "";
                    $.each(productForm, function (ii, ee) {
                        if ($(ee).is(":checked")) {
                            content_ids = $(ee).val();
                            value = $(ee).parent('label').text();
                            record_value = $(ee).parent('label').text();
                        }
                    })
                    var obj = {
                        property_id: $(e).attr('property_id'),
                        name: $(e).attr('name'),
                        fixed_name: $(e).attr('name'),
                        required: $(e).attr('require'),
                        order_id: order_id,
                        content_ids: content_ids,
                        value: value,
                        record_value: record_value
                    }
                }
                if (productForm.attr('productForm') == 'textarea') {
                    var obj = {
                        property_id: $(e).attr('property_id'),
                        name: $(e).attr('name'),
                        fixed_name: $(e).attr('name'),
                        required: $(e).attr('require'),
                        order_id: order_id,
                        value: productForm.val(),
                        record_value: productForm.val()
                    }
                }
                if (productForm.attr('productForm') == 'checkbox') {
                    var content_ids = "";
                    var value = "";
                    var record_value = "";
                    $.each(productForm, function (ii, ee) {
                        if ($(ee).is(":checked")) {
                            content_ids += $(ee).val() + ',';
                            value += $(ee).parent('label').text() + ',';
                            record_value += $(ee).parent('label').text() + ',';
                        }
                    })
                    content_ids = content_ids.substring(0, content_ids.length - 1)
                    value = value.substring(0, value.length - 1)
                    record_value = record_value.substring(0, record_value.length - 1)
                    var obj = {
                        property_id: $(e).attr('property_id'),
                        name: $(e).attr('name'),
                        fixed_name: $(e).attr('name'),
                        required: $(e).attr('require'),
                        order_id: order_id,
                        content_ids: content_ids,
                        value: value,
                        record_value: record_value
                    }
                }
                //if (obj.required == '1' || obj.value != '') {
                productInfos.push(obj);
                //}
            })


            var productFeeInfos = new Array();

            var charging = $("input[fee_id]");

            $.each(charging, function (i, e) {
                var obj = {
                    fee_id: $(e).attr("fee_id"),
                    name: $(e).attr('name'),
                    fixed_name: $(e).attr('name'),
                    required: $(e).attr('require'),
                    order_id: order_id,
                    fee: $(e).val(),
                    record_value: $(e).val()
                }
                productFeeInfos.push(obj);
            })


            var loanInfos = new Array();

            var loan = $("input[loan_id]:checked");
            if (loan.length) {
                loanInfos.push({
                    loan_id: loan.attr("loan_id"),
                    order_id: order_id,
                    required: '1',
                    value: loan.parent('label').text(),
                    record_value: loan.parent('label').text()
                })
            }

            var orderInfos = new Array();

            var column = $("[column_key]")
            $.each(column, function (i, e) {
                if ($(e).attr('column_key') == 'loan_way') {
                    var value = $(e).find('input[type="radio"]:checked').val();
                    var record_value = $(e).find('input[type="radio"]:checked').parent('label').text();
                    var obj = {
                        order_id: order_id,
                        column_key: $(e).attr('column_key'),
                        name: $(e).attr('name'),
                        fixed_name: $(e).attr('name'),
                        required: $(e).attr('require'),
                        value: value ? value : "",
                        record_value: record_value
                    }
                }
                else if ($(e).attr('column_key') == 'apply_money') {
                    var obj = {
                        order_id: order_id,
                        column_key: $(e).attr('column_key'),
                        name: $(e).attr('name'),
                        fixed_name: $(e).attr('name'),
                        required: $(e).attr('require'),
                        value: parseInt(Constant.fn.toNum($(e).val())) ? parseInt(Constant.fn.toNum($(e).val())) : "",
                        record_value: parseInt(Constant.fn.toNum($(e).val()))
                    }
                }
                else if ($(e).attr('column_key') == 'interest') {
                    var obj = {
                        order_id: order_id,
                        column_key: $(e).attr('column_key'),
                        name: $(e).attr('name'),
                        fixed_name: $(e).attr('name'),
                        required: $(e).attr('require'),
                        value: $(e).val(),
                        record_value: $(e).val()
                    }
                }
                else {
                    var option = $(e).find('option:selected');
                    var obj = {
                        order_id: order_id,
                        column_key: $(e).attr('column_key'),
                        name: $(e).attr('name'),
                        fixed_name: $(e).attr('name'),
                        required: $(e).attr('require'),
                        value: option.data('id') ? option.data('id') : "",
                        record_value: option.data('id') ? option.text() : ""
                    }
                }
                orderInfos.push(obj);
            })


            var frontData = {
                productInfos: productInfos,
                productFeeInfos: productFeeInfos,
                orderInfos: orderInfos
            }

            var productInfos = frontData.productInfos;
            var productFeeInfos = frontData.productFeeInfos;
            var orderInfos = frontData.orderInfos;


            for (var i = 0; i < productInfos.length; i++) {
                if (productInfos[i].required == '1' && !productInfos[i].value) {
                    Constant.fn.Message('I', '请填写' + productInfos[i].name);
                    return;
                }
            }

            for (var i = 0; i < productFeeInfos.length; i++) {
                if (productFeeInfos[i].required == '1' && !productFeeInfos[i].fee) {
                    Constant.fn.Message('I', '请填写' + productFeeInfos[i].name);
                    return;
                }
            }

            for (var i = 0; i < orderInfos.length; i++) {
                if (orderInfos[i].required == '1' && !orderInfos[i].value) {
                    Constant.fn.Message('I', '请填写' + orderInfos[i].name);
                    return;
                }
            }


            //验证是否选择角色
            if (approvalType == '2') {
                var userId = "";
                $.each($('.choose-per'), function (i, e) {
                    userId += $(e).data('userid') + ',';
                })
                userId = userId.substring(0, userId.length - 1);
            }
            else {
                var userId = $("#role_select option:selected").val();
            }
            var type = $(".processForm_winBox input[name='faceResult']:checked").val();
            var remark = $(".processForm_winBox .approveRemark").val();
            //if (last_node_id != node_id) {
            if (type == '1' && !userId) {
                Constant.fn.Message('I', '请选择审批角色');
                return;
            }
            //}
            if (!type) {
                Constant.fn.Message('I', '请选择审核结果');
                return;
            }
            if (!remark) {
                Constant.fn.Message('I', '请输入备注');
                return;
            }
            ;

            site.send({
                url: url.saveNodefromInfos,
                data: {
                    frontData: JSON.stringify(frontData)
                },
                callback: function (data) {
                    data = JSON.parse(data)
                    if (data.type == '1') {
                        saveImg(userId, type, remark);
                        //roamTask(userId, type, remark);
                    } else {
                        Constant.fn.Message("F", data.msg);
                    }
                }
            })

        }

        //点击流转
        $("#roamTask").click(function (e) {
            saveNodefromInfos();
        })

        // WebUploader实例
        var uploader;
        var attachId, attachName, order_num;
        var type;
        var success = false;


        function OSS_IMAGE_INIT(order_id, node_id) {

            var objdata = {
                upfile_nametype: 'random_name',//local_name random_name  上传文件的文件名类型
                url: localStorage.getItem('host') + "oss/getSignature.do"
            };
            // 当domReady的时候开始初始化
            $(".viewPic").unbind().on('click', function () {
                type = $(this).siblings('._result').find('input[type=radio]:checked').val()
                attachId = $(this).data('id');
                attachName = $(this).data('attachname');
                order_num = $('.public-content-Po').html();

                /!*if (!order_id) {
                    Constant.fn.Message('I', '请先录入订单');
                    //$("#viewPic").unbind();
                    return
                }*!/

                /!*if(!attach_id){
                    $("#attachmentType").addClass('error');
                    Constant.fn.Message('I','请选择类型');
                    return
                }*!/

                timeout : 30000,
                    $.ajax({
                        type: "post",
                        url: objdata.url,
                        success: function (str) {
                            data = JSON.parse(str)
                            if (data.type > 0) {
                                try {
                                    var re = data.content;
                                    objdata.osssignature = {
                                        'key': re.dir,
                                        'policy': re.policy,
                                        'OSSAccessKeyId': re.accessId,
                                        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                                        'signature': re.signature,
                                        'callback': re.callback,
                                        'expire': re.expire,
                                        'host': re.host
                                    };
                                } catch (e) {
                                    alert("系统错误");
                                }

                            } else {
                                alert("结果为空");
                            }
                            $("#image_upload_pop").toggle();

                            //设置居中
                            centerPosition($("#image_upload_pop .edui-dialog-body").get(0));
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            // alert("ajax error");
                        },
                        complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
                            if (status == 'timeout') {
                                //alert('请求超时，请稍后再试！');
                            }
                        },
                        async: false
                    });

                if (uploader) {
                    return;
                }///界面已经存在，不去重新创建uploader了

                var $wrap = $('#uploader'),
                    // 图片容器
                    $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList')),

                    // 状态栏，包括进度和控制按钮
                    $statusBar = $wrap.find('.statusBar'),

                    // 文件总体选择信息。
                    $info = $statusBar.find('.info'),

                    // 上传按钮
                    $upload = $wrap.find('.uploadBtn'),

                    // 没选择文件之前的内容。
                    $placeHolder = $wrap.find('.placeholder'),

                    $progress = $statusBar.find('.progress').hide(),

                    // 添加的文件数量
                    fileCount = 0,

                    // 添加的文件总大小
                    fileSize = 0,

                    acceptExtensions = [".png",".tif",".TIF", ".pdf", ".jpg", ".jpeg", ".gif", ".bmp", ".xls", ".xlsx"].join('').replace(/\./g, ',').replace(/^[,]/, ''),

                    // 优化retina, 在retina下这个值是2
                    ratio = window.devicePixelRatio || 1,

                    // 缩略图大小
                    thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio,

                    // 可能有pedding, ready, uploading, confirm, done.
                    state = 'pedding',

                    // 所有文件的进度信息，key为file id
                    percentages = {},
                    // 判断浏览器是否支持图片的base64
                    isSupportBase64 = (function () {
                        var data = new Image();
                        var support = true;
                        data.onload = data.onerror = function () {
                            if (this.width != 1 || this.height != 1) {
                                support = false;
                            }
                        }
                        data.src = "";
                        return support;
                    })(),

                    // 检测是否已经安装flash，检测flash的版本
                    flashVersion = (function () {
                        var version;

                        try {
                            version = navigator.plugins['Shockwave Flash'];
                            version = version.description;
                        } catch (ex) {
                            try {
                                version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
                            } catch (ex2) {
                                version = '0.0';
                            }
                        }
                        version = version.match(/\d+/g);
                        return parseFloat(version[0] + '.' + version[1], 10);
                    })(),

                    supportTransition = (function () {
                        var s = document.createElement('p').style,
                            r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s;
                        s = null;
                        return r;
                    })(), _this = this;

                _this.imageList = [];
                if (!WebUploader.Uploader.support('flash') /!* && WebUploader.browser.ie *!/) {

                    // flash 安装了但是版本过低。
                    if (flashVersion) {
                        (function (container) {
                            window['expressinstallcallback'] = function (state) {
                                switch (state) {
                                    case 'Download.Cancelled':
                                        alert('您取消了更新！')
                                        break;

                                    case 'Download.Failed':
                                        alert('安装失败')
                                        break;

                                    default:
                                        alert('安装已成功，请刷新！');
                                        break;
                                }
                                delete window['expressinstallcallback'];
                            };

                            var swf = './expressInstall.swf';
                            // insert flash object
                            var html = '<object type="application/' + 'x-shockwave-flash" data="' + swf + '" ';

                            if (WebUploader.browser.ie) {
                                html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
                            }

                            html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + swf + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>';

                            container.html(html);

                        })($wrap);

                        // 压根就没有安装。
                    } else {
                        $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
                    }

                    return;
                } else if (!WebUploader.Uploader.support()) {
                    alert('Web Uploader 不支持您的浏览器！');
                    return;
                }


                // 实例化
                uploader = WebUploader.create({
                    pick: {
                        id: '#filePicker',
                        label: '点击选择图片'
                    },
                    resize: false,
                    duplicate: true,
                    accept: {
                        title: 'Images',
                        extensions: acceptExtensions,
                        // mimeTypes: 'filed/!*' //wuzhifeng 修改上传文件类型 图片的话 是
                        // image
                        mimeTypes: 'image/!*'
                    },
                    formData: {
                        uid: 123
                    },
                    dnd: '#edui114_body',
                    paste: '#uploader',
                    swf: '/tbpt/plugin/ueditor/third-party/webuploader/Uploader.swf',
                    chunked: false,
                    compress: false,
                    chunkSize: 512 * 1024,
                    server: objdata.osssignature.host,///tbpt/plugin/ueditor/jsp/controller.jsp?action=uploadimage
                    //http://oss.aliyuncs.com/ http://tbptfile.oss-cn-beijing.aliyuncs.com/
                    // runtimeOrder: 'flash',
                    // server:
                    // 'http://liaoxuezhi.fe.baidu.com/webupload/fileupload.php',
                    // server: 'http://www.2betop.net/fileupload.php',
                    //

                    // accept: {
                    // title: 'Images',
                    // extensions: 'gif,jpg,jpeg,bmp,png',
                    // mimeTypes: 'image/!*'
                    // },

                    // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
                    disableGlobalDnd: false,
                    auto: false,// {Boolean} [可选] [默认值：false] 设置为 true
                    // 后，不需要手动调用上传，有文件选择即开始上传。
                    fileNumLimit: 300,// 验证文件总数量, 超出则不允许加入队列。
                    fileSizeLimit: 200 * 1024 * 1024, // 200 M
                    fileSingleSizeLimit: 110 * 1024 * 1024 // 50 M
                });

                // 拖拽时不接受 js, txt 文件。
                uploader.on('dndAccept', function (items) {
                    var denied = false, len = items.length, i = 0,
                        // 修改js类型
                        unAllowed = 'text/plain;application/javascript ';

                    for (; i < len; i++) {
                        // 如果在列表里面
                        if (~unAllowed.indexOf(items[i].type)) {
                            denied = true;
                            break;
                        }
                    }

                    return !denied;
                });
                // 添加“添加文件”的按钮，
                uploader.addButton({
                    id: '#filePicker2',
                    label: '继续添加'
                });

                uploader.on('ready', function () {
                    window.uploader = uploader;
                });

                //上传完成 服务器响应 不代表上传成功
                uploader.on('uploadSuccess', function (file, ret) {
                    //console.log(fileCount);
                    //console.log(responseText);
                    var $file = $('#' + file.id);
                    if (ret._raw) {
                        _this.imageList[$file.index()] = {
                            succ: true
                        };
                        $file.append('<span class="success"></span>');
                        //图片
                        if (file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/tiff') {
                            //console.log($file.index());
                            var index = $file.index();
                            /!*if ($file.index() == 0) {
                                $('#picStay').prepend('原图:<a sort="' + $file.index() + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                                $('#picStay').prepend('<img sort="' + $file.index() + '" src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_lfit,h_56,w_36" />');
                            } else {*!/
                            var aSortArr = [];
                            if (!$('#picStay a').length) {
                                $('#picStay').prepend('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            } else {
                                $.each($('#picStay a'), function (i, e) {
                                    if ($(e).attr('sort') < index) {
                                        aSortArr.push($(e).attr('sort'))
                                    }
                                })

                                if (aSortArr.length) {
                                    $("#picStay a").eq(aSortArr.length - 1).after('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                                }
                                else {
                                    $('#picStay').prepend('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                                }
                            }


                            var imgSortArr = [];
                            if (!$('#picStay img').length) {
                                $('#picStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" />');
                            } else {
                                $.each($('#picStay img'), function (i, e) {
                                    if ($(e).attr('sort') < index) {
                                        imgSortArr.push($(e).attr('sort'))
                                    }
                                })

                                if (imgSortArr.length) {
                                    $("#picStay img").eq(imgSortArr.length - 1).after('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" />');
                                } else {
                                    $('#picStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" />');
                                }
                            }
                        }
                    } else {
                        showError(file.statusText);
                        $file.find('.error').text("失败").show();
                        console.log("上传失败");
                        $('body').append("上传失败");
                    }

                });

                uploader.on('uploadBeforeSend', function (obj, data, headers) {
                    //TODO   如果同一个页面上传多次  需要处理签名逻辑   不用每次都签名
                    //debugger
                    //赋值参数
                    data = $.extend(data, objdata.osssignature);
                    headers['Access-Control-Allow-Origin'] = "*";

                    //设置文件路径
                    data.key = data.key + "/" + calculate_object_name(data.name, objdata.upfile_nametype);
                    obj.filepath = data.key;
                    obj.file.path = data.key;
                });

                //得到文件名 type local_name random_name
                function calculate_object_name(filename, type) {
                    if (type && type == 'local_name') {
                        return "${filename}";
                    } else {//随机生成文件名
                        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                        var maxPos = chars.length;
                        var random_string = '';
                        for (i = 0; i < 10; i++) {
                            random_string += chars.charAt(Math.floor(Math.random() * maxPos));
                        }
                        var pos = filename.lastIndexOf('.')
                        var suffix = ''
                        if (pos != -1) {
                            suffix = filename.substring(pos);
                        }
                        return random_string + new Date().getTime() + suffix;
                    }
                }

                // 当有文件添加进来时执行，负责view的创建
                function addFile(file) {
                    var $li = $('<li id="' + file.id + '">' + '<p class="title">' + file.name + '</p>' + '<p class="imgWrap"></p>' + '<p class="progress"><span></span></p>' + '</li>'),

                        $btns = $('<div class="file-panel">' + '<span class="cancel">删除</span>' + '<span class="rotateRight">向右旋转</span>' + '<span class="rotateLeft">向左旋转</span></div>').appendTo($li),
                        $prgress = $li.find('p.progress span'), $wrap = $li.find('p.imgWrap'),
                        $info = $('<p class="error"></p>'),

                        showError = function (code) {
                            switch (code) {
                                case 'exceed_size':
                                    text = '文件大小超出';
                                    break;

                                case 'interrupt':
                                    text = '上传暂停';
                                    break;

                                default:
                                    text = '上传失败，请重试';
                                    break;
                            }

                            $info.text(text).appendTo($li);
                        };

                    if (file.getStatus() === 'invalid') {
                        showError(file.statusText);
                    } else {
                        // @todo lazyload
                        $wrap.text('预览中');
                        uploader.makeThumb(file, function (error, src) {
                            var img;

                            if (error) {
                                $wrap.text('不能预览');
                                return;
                            }

                            if (isSupportBase64) {
                                img = $('<img src="' + src + '">');
                                $wrap.empty().append(img);
                            }
                        }, thumbnailWidth, thumbnailHeight);

                        percentages[file.id] = [file.size, 0];
                        file.rotation = 0;
                    }

                    file.on('statuschange', function (cur, prev) {
                        if (prev === 'progress') {
                            $prgress.hide().width(0);
                        } else if (prev === 'queued') {
                            $li.off('mouseenter mouseleave');
                            $btns.remove();
                        }
                        // 成功
                        if (cur === 'error' || cur === 'invalid') {
                            console.log(file.statusText);
                            showError(file.statusText);
                            percentages[file.id][1] = 1;
                        } else if (cur === 'interrupt') {
                            showError('interrupt');
                        } else if (cur === 'queued') {
                            percentages[file.id][1] = 0;
                        } else if (cur === 'progress') {
                            $info.remove();
                            $prgress.css('display', 'block');
                        } else if (cur === 'complete') {
                            //$li.append('<span class="success"></span>');
                        }

                        $li.removeClass('state-' + prev).addClass('state-' + cur);
                    });
                    uploader.on('uploadAccept', function (file, response) {
                        var hasError = (response['error'] !== undefined);
                        if (hasError) {
                            // 通过return false来告诉组件，此文件上传有错。
                            return false;
                        }
                        ;
                    });
                    uploader.on("uploadFinished", function () {
                        success = true;
                        // uploader.reset();
                        // uploader;
                    });

                    $li.on('mouseenter', function () {
                        $btns.stop().animate({
                            height: 30
                        });
                    });

                    $li.on('mouseleave', function () {
                        $btns.stop().animate({
                            height: 0
                        });
                    });

                    $btns.on('click', 'span', function () {
                        var index = $(this).index(), deg;

                        switch (index) {
                            case 0:
                                uploader.removeFile(file);
                                return;

                            case 1:
                                file.rotation += 90;
                                break;

                            case 2:
                                file.rotation -= 90;
                                break;
                        }

                        if (supportTransition) {
                            deg = 'rotate(' + file.rotation + 'deg)';
                            $wrap.css({
                                '-webkit-transform': deg,
                                '-mos-transform': deg,
                                '-o-transform': deg,
                                'transform': deg
                            });
                        } else {
                            $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
                        }

                    });

                    $li.appendTo($queue);
                }

                // 负责view的销毁
                function removeFile(file) {
                    var $li = $('#' + file.id);

                    delete percentages[file.id];
                    updateTotalProgress();
                    $li.off().find('.file-panel').off().end().remove();
                }

                function updateTotalProgress() {
                    var loaded = 0, total = 0, spans = $progress.children(), percent;

                    $.each(percentages, function (k, v) {
                        total += v[0];
                        loaded += v[0] * v[1];
                    });

                    percent = total ? loaded / total : 0;

                    spans.eq(0).text(Math.round(percent * 100) + '%');
                    spans.eq(1).css('width', Math.round(percent * 100) + '%');
                    updateStatus();
                }

                function updateStatus() {
                    var text = '', stats;

                    if (state === 'ready') {
                        text = '选中' + fileCount + '张图片，共' + WebUploader.formatSize(fileSize) + '。';
                    } else if (state === 'confirm') {
                        stats = uploader.getStats();
                        if (stats.uploadFailNum) {
                            text = '已成功上传' + stats.successNum + '张照片，' + stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
                        }

                    } else {
                        stats = uploader.getStats();
                        text = '共' + fileCount + '张（' + WebUploader.formatSize(fileSize) + '），已上传' + stats.successNum + '张';

                        if (stats.uploadFailNum) {
                            text += '，失败' + stats.uploadFailNum + '张';
                        }
                    }

                    $info.html(text);
                }

                function setState(val) {
                    var file, stats;

                    if (val === state) {
                        return;
                    }

                    $upload.removeClass('state-' + state);
                    $upload.addClass('state-' + val);
                    state = val;

                    switch (state) {
                        case 'pedding':
                            $placeHolder.removeClass('element-invisible');
                            $queue.hide();
                            $statusBar.addClass('element-invisible');
                            uploader.refresh();
                            break;

                        case 'ready':
                            $placeHolder.addClass('element-invisible');
                            $('#filePicker2').removeClass('element-invisible');
                            $queue.show();
                            $statusBar.removeClass('element-invisible');
                            uploader.refresh();
                            $upload.text('开始上传').removeClass('disabled');
                            break;

                        case 'uploading':
                            $('#filePicker2').addClass('element-invisible');
                            $progress.show();
                            $upload.text('暂停上传');
                            break;

                        case 'paused':
                            $progress.show();
                            $upload.text('继续上传');
                            break;

                        case 'confirm':
                            $progress.hide();
                            $upload.text('开始上传').addClass('disabled');

                            stats = uploader.getStats();
                            if (stats.successNum && !stats.uploadFailNum) {
                                setState('finish');
                                return;
                            }
                            break;
                        case 'finish':
                            stats = uploader.getStats();
                            if (stats.successNum) {

                                // WuZhiFeng

                            } else {
                                // 没有成功的图片，重设
                                state = 'done';
                                location.reload();
                            }
                            $('#filePicker2').removeClass('element-invisible');
                            $upload.text('开始上传').removeClass('disabled');
                            break;
                    }

                    updateStatus();
                }

                uploader.onUploadProgress = function (file, percentage) {
                    var $li = $('#' + file.id), $percent = $li.find('.progress span');

                    $percent.css('width', percentage * 100 + '%');
                    if ($.isEmptyObject(percentages)) {
                        return false;
                    }
                    percentages[file.id][1] = percentage;
                    updateTotalProgress();
                };

                uploader.onFileQueued = function (file) {
                    fileCount++;
                    fileSize += file.size;

                    if (fileCount === 1) {
                        $placeHolder.addClass('element-invisible');
                        $statusBar.show();
                    }

                    addFile(file);
                    setState('ready');
                    updateTotalProgress();
                };

                uploader.onFileDequeued = function (file) {
                    fileCount--;
                    fileSize -= file.size;

                    if (!fileCount) {
                        setState('pedding');
                    }

                    removeFile(file);
                    updateTotalProgress();

                };

                uploader.on('all', function (type) {
                    var stats;
                    switch (type) {
                        case 'uploadFinished':
                            setState('confirm');
                            break;

                        case 'startUpload':
                            setState('uploading');
                            break;

                        case 'stopUpload':
                            setState('paused');
                            break;

                    }

                });

                uploader.onError = function (code) {
                    if (code == 'Q_TYPE_DENIED') {
                        alert("不支持该文件类型，请选择图片类型文件");
                    }
                    if (code == 'Q_EXCEED_NUM_LIMIT') {
                        alert("只能上传单张图片");
                    }
                    // alert( 'Eroor: ' + code );
                };

                $upload.on('click', function () {
                    if ($(this).hasClass('disabled')) {
                        return false;
                    }

                    if (state === 'ready') {
                        uploader.upload();
                    } else if (state === 'paused') {
                        uploader.upload();
                    } else if (state === 'uploading') {
                        uploader.stop();
                    }
                });

                $info.on('click', '.retry', function () {
                    uploader.retry();
                });

                $info.on('click', '.ignore', function () {
                    alert('todo');
                });

                $upload.addClass('state-' + state);
                updateTotalProgress();


            });
        }

        var resetUploader = function () {
            if (uploader) {
                //重新设置页面
                for (var i = 0; i < uploader.getFiles().length; i++) {
                    uploader.removeFile(uploader.getFiles()[i]);
                }
                uploader.stop();
                uploader.reset();
            }
            $('.webuploader-element-invisible').val('');
        };

        $(".closed").unbind();
        $(".sure").unbind();


        $(".sure").on('click', function () {

            var attachImg = [];
            var attachimg = [];
            var flag2 = false;
            $('#image_upload_pop').toggle();
            resetUploader();

            var img = $("#picStay a");

            if (img.length) {
                $.each(img, function (i, e) {
                    attachImg.push(
                        {
                            playHref: $(e).attr('playhref'),
                            href: $(e).attr('href'),
                            attachId: attachId
                        }
                    );
                })

                $.each(img, function (i, e) {
                    attachimg.push($(e).attr('href'))
                })

                var sameAttach = $('[attachid=' + attachId + '] li');
                if (sameAttach.length) {
                    $.each(sameAttach, function (i, e) {
                        attachimg.push($(e).attr('href'))
                    })
                }
            }

            if (attachImg.length) {
                if ($('[attachId]').length) {
                    $.each($('[attachId]'), function (i, e) {
                        if (attachImg[0].attachId == $(e).attr('attachId')) {
                            $.each(attachImg, function (ii, ee) {
                                $(e).append('<li href=\"' + ee.href + '\">   \n' +
                                    '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                    '<i class="delSingleAttach iconfont icon-minus">\n' +
                                    '</i>\n' +
                                    '</li>')
                            })

                            $("#picStay").html("");
                            flag2 = false;
                        }
                    })

                    if (flag2) {
                        $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content[0].id + "></div></td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                        $.each(attachImg, function (ii, ee) {
                            var gallery = $('[attachId=' + ee.attachId + ']');
                            gallery.append('<li href=\"' + ee.href + '\">   \n' +
                                '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                '<i class="delSingleAttach iconfont icon-minus">\n' +
                                '</i>\n' +
                                '</li>')
                        })

                        //imgList(data.content[0].attachId);
                        $("#picStay").html("");
                    }
                }

                else {
                    $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content[0].id + "></div></td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                    $.each(attachImg, function (ii, ee) {
                        var gallery = $('[attachId=' + ee.attachId + ']');
                        gallery.append('<li href=\"' + ee.href + '\">   \n' +
                            '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                            '<i class="delSingleAttach iconfont icon-minus">\n' +
                            '</i>\n' +
                            '</li>')
                    })

                    //imgList(data.content[0].attachId);
                    $("#picStay").html("");
                }
                $('.processForm_winBox .winBox1').viewer('destroy').viewer();
                Constant.fn.initScroll();
            }
            //删除单张图片
            $('.delSingleAttach').unbind().on('click', function (e) {
                e.stopPropagation();
                e.preventDefault();
                $(this).parents('li').remove();

                Constant.fn.initScroll();
            })
        })

        $(".closed").on('click', function () {
            //uploader.stop();
            //uploader.reset();
            resetUploader();
            //uploader.destroy();
            $('#image_upload_pop').toggle();
            $("#picStay").html("");
        })

        //节点表单审核单选按钮
        $('input[name="faceResult"][value="1"]').on('change', function () {
            queryRole(order_id);
        })

        $('input[name="faceResult"][value="2"]').on('change', function () {
            $('.role').remove();
            $('.chooseRole').remove();
        })

        /!**
         * 从ueditor.all.js里面拷贝的拖拽方法
         *!/

        var centerPosition = function (el) {
            var uiUtils = baidu.editor.ui.uiUtils;
            var vpRect = uiUtils.getViewportRect();
            var rect = uiUtils.getClientRect(el);
            var left = vpRect.width / 2 - rect.width / 2;
            var top = vpRect.height / 2 - rect.height / 2;
            el.style.left = Math.max(left, 0) + 'px';
            el.style.top = Math.max(top, 0) + 'px';
        };
    }*/

    //detail();
})